<template>
            <h1>购物车</h1>
            <table>
                        <tr>
                            <th>编号</th>
                            <th>商品</th>
                            <th>价格</th>
                            <th>数量</th>

                        </tr>

                        <tr v-for="item in  tableData"  :key="item.id">
                            <td><input  type="checkbox"  :value="item.id"  v-model="checkData"/></td>
                            <td>{{item.id}}</td>
                            <td>{{item.productName}}</td>
                            <td>{{item.productPrice}}</td>
                            <td>{{item.productCount}}</td>
                        </tr>


            </table>


      <div>总价：{{sumTotalPrice}}     总计:{{sumTotalCount}}</div>       你选中的id:{{checkData}}   总价：{{sumSelectPrice}}



</template>
<script setup>

import { computed, onMounted, ref, watch } from 'vue';

    const  checkData  =ref([])



    const  tableData=ref([
            {
               id:"1",
               title:"张三的购物车",
               productId:"1",
               productName:"鞋子",
               productCount:2,
               productPrice:200,
               userId:"1"

            },
            {
               id:"2",
               title:"张三的购物车",
               productId:"2",
               productName:"袜子",
               productCount:5,
               productPrice:5,
               userId:"1"

            },
            {
               id:"3",
               title:"张三的购物车",
               productId:"2",
               productName:"袜子",
               productCount:5,
               productPrice:5,
               userId:"1"

            }


    ])

    onMounted(()=>{
        /* fetch("https://localhost:3000/carts").then(res=>res.json()).then(data=>{
                tableData.value=data;

            })

        */
    })


    //计算属性
    const  sumTotalPrice =computed(()=>{
        let sum =0;
        for(let  i=0;i<tableData.value.length;i++){
            sum  += tableData.value[i].productCount* tableData.value[i].productPrice;
        }
        return   sum;
    })



    const  sumTotalCount =computed(()=>{
        let sum =0;
        for(let  i=0;i<tableData.value.length;i++){
            sum  += tableData.value[i].productCount;
        }
        return   sum;
    })

    const  sumSelectPrice=ref(0)   //总价
    
    watch(checkData,(n ,old)=>{
        let sum =0;
        for(let  i=0;i<tableData.value.length;i++){
            if(n.includes(tableData.value[i].id)){
                sum  += tableData.value[i].productCount* tableData.value[i].productPrice;

            }
        }

        sumSelectPrice.value=sum;


    })





</script>
